#include <stdio.h>
#include <unistd.h>
#include <stdlib.h>
#include <string.h>
#include <sys/types.h>
#include <sys/wait.h>

int main()
{
  int pipefd[2];
  int ret = pipe(pipefd);
  if (ret == -1){
    // 管道创建失败
    perror("make piep");
    exit(-1);
  }
  // 成功返回0
  // pipefd[0] 代表读端
  // pipefd[1] 代表写端
  //printf("fd[0]:%d, fd[1]:%d\n", pipefd[0], pipefd[1]);
  //char buf[64] = "hello world";
  //// 写数据
  //write(pipefd[1], buf, sizeof(buf)/sizeof(buf[0]));
  //// 读数据
  //buf[0] = 0;// 清空buf
  //ssize_t s = read(pipefd[0], buf, 11);
  //buf[s] = '\0';
  //printf("%s\n", buf);
  pid_t id = fork();
  if (id < 0){
    perror("fork failed");
    exit(-1);
  }
  else if (id == 0){
    // child
    // 关闭读端
    close(pipefd[0]);
    const char* msg = "I am child...!\n";
    // int count = 0;
    // 写数据
    while (1){
      ssize_t s = write(pipefd[1], msg, strlen(msg));
      //sleep(5);// 管道大部分时间是空的，读条件不满足时，读端处于阻塞状态
      printf("child is sending message...\n");
      
      //printf("CHILD: %d\n", count++);
      //if (count == 5){
      //  close(pipefd[1]);
      //  exit(-1);
      //}
      sleep(1);
    }
  }
  else{
    // parent
    close(pipefd[1]);
    char buf[64];
    int count = 0;
    while (1){
      ssize_t s = read(pipefd[0], buf, sizeof(buf)/sizeof(buf[0])-1);
      if (s > 0){
        buf[s] = '\0';// 字符串后放一个'\0'
        printf("father get message:%s", buf);
        //sleep(5);// 管道大部分时间都是满的，写条件不满足时，写端处于阻塞状态
      }
      else if (s == 0){
        // 读到文件结尾  写端关闭文件描述符 读端会读到文件结尾
        printf("father read end of file...\n ");
      }
      sleep(1);
      if (count++ == 3){
        close(pipefd[0]);// 读端关闭文件描述符，写端进程后序会被操作系统直接杀掉，没有进程读，写时没有意义的
        break;
      }
    }
    int status;
    pid_t ret = waitpid(id, &status, 0);
    if (ret > 0){
      // 等待成功
      printf("child exit singal is %d\n", status&0x7f);
    }
    else{
      // 等待失败
      perror("wait failed");
      exit(-1);
    }
  }

  return 0;
}
